<template>
  <div class="app-container">
    <!-- 搜索 -->
    <el-card class="box-card">
      <el-row type="flex" align="middle">
        <el-col :span="12">
          <div class="grid-content bg-purple search">
            <el-form ref="query" :model="query" label-width="100px">
              <el-form-item style="margin-bottom:0px" label="类型">
                <el-select v-model="query.keywords" placeholder="请选择活类型">
                  <el-option label="商城" value="1"></el-option>
                  <el-option label="背包" value="2"></el-option>
                </el-select>
              </el-form-item>
            </el-form>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="grid-content bg-purple-light" style="text-align:right">
            <el-button type="primary" @click="queryAsk">查询</el-button>
            <el-button @click="queryReset">重置</el-button>
          </div>
        </el-col>
      </el-row>
    </el-card>
    <el-card class="box-card">
      <el-button type="primary" style="margin-bottom:20px" @click="addList">添加</el-button>
      <el-table
        :data="tableData"
        :header-cell-style="{background:'#eee'}"
        border
        v-loading="loading"
        style="width: 100%;margin-bottom: 20px;"
      >
        <el-table-column align="center" type="index" width="50" label="序号"></el-table-column>
        <el-table-column align="center" prop="name" label="分类">
          <template slot-scope="scope">
            <div v-if="scope.row.type==1">商城</div>
            <div v-if="scope.row.type==2">背包</div>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="money" label="邮费"></el-table-column>
        <el-table-column align="center" prop="update_time" label="背包多少件包邮">
          <template slot-scope="scope">
            <div v-if="scope.row.type==1">-</div>
            <div v-if="scope.row.type==2">{{scope.row.num}}</div>
          </template>
        </el-table-column>
        <el-table-column align="center" show-overflow-tooltip label="省/市信息">
          <template slot-scope="scope">
            <div v-if="scope.row.type==1">{{scope.row.province_names}}</div>
            <div v-if="scope.row.type==2">{{scope.row.city_names}}</div>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="update_time" label="更新时间"></el-table-column>
        <el-table-column align="center" fixed="right" label="操作" width="150">
          <template slot-scope="scope">
            <el-button @click="handleEdite(scope.row)" type="text" size="small">编辑</el-button>
            <el-popconfirm
              confirmButtonText="好的"
              cancelButtonText="不用了"
              icon="el-icon-info"
              iconColor="red"
              title="这是一段内容确定删除吗？"
              @onConfirm="handleDelete(scope.row)"
            >
              <el-button
                style="margin-left:10px;color:red"
                slot="reference"
                type="text"
                size="small"
              >删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 抽屉 -->
    <el-drawer
      :title="title"
      :visible.sync="drawer"
      :direction="direction"
      :before-close="handleClose"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" style="margin-left:50px">
        <el-form-item label="类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择类型">
            <el-option label="商城" value="1"></el-option>
            <el-option label="背包" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="省/市" prop="data">
          <el-cascader
            v-model="form.data"
            :disabled="!form.type"
            :options="options"
            :props="props"
            collapse-tags
            clearable
            placeholder="请选择省/市"
            @visible-change="getProvince"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="多少件包邮" prop="num">
          <el-input v-model="form.num" placeholder="请输入多少件包邮" :disabled="form.type==1"></el-input>
        </el-form-item>
        <el-form-item label="运费" prop="money">
          <el-input v-model="form.money" placeholder="请输入运费"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">确定</el-button>
          <el-button @click="subCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>

<script>
import {
  freightList,
  getaddress,
  addFreight,
  editFreight,
  delFreight
} from "@/api/freight";
import { parseTime } from "@/utils/index";

export default {
  name: "FreightList",
  data() {
    return {
      tableData: [],
      // 编辑抽屉
      drawer: false,
      direction: "rtl",
      title: "编辑",
      //input
      query: {
        keywords: ""
      },
      form: {
        data: "",
        num: "",
        money: "",
        type: "",
        province_str: [],
        city_str: [],
        id: ""
      },
      rules: {
        data: [{ required: true, message: "请选择地址", trigger: "blur" }],
        num: [
          { required: true, message: "请选输入多少件包邮", trigger: "blur" }
        ],
        money: [{ required: true, message: "请输入运费", trigger: "blur" }],
        type: [{ required: true, message: "请选类型", trigger: "blur" }]
      },
      loading: false,
      props: {
        multiple: true,
        value: "oid",
        label: "name",
        children: "child",
        disabled: "is_select"
      },
      options: []
    };
  },
  mounted() {
    this.getList();
  },
  methods: {
    async getList() {
      this.loading = true;
      const res = await freightList({ type: this.query.keywords });
      this.loading = false;
      this.tableData = res.data;
      this.tableData.forEach(item => {
        if (item.update_time == 0) {
          item.update_time = "-";
        } else {
          item.update_time = parseTime(
            item.update_time,
            "{y}-{m}-{d} {h}:{i}:{s}"
          );
        }
      });
    },
    queryAsk() {
      this.getList();
    },
    //重置
    queryReset() {
      this.resetForm("query");
      this.query.keywords = "";
      this.getList();
    },
    // 获取省
    async getProvince() {
      const res = await getaddress({ type: this.form.type, id: this.form.id });
      console.log(res);
      this.options = res.data;
    },
    addList() {
      this.getProvince();
      this.drawer = true;
      this.title = "添加";
    },
    handleEdite(row) {
      this.drawer = true;
      this.title = "编辑";
      const form = {
        data: JSON.parse(row.data),
        num: row.num,
        money: row.money,
        type: row.type,
        province_str: row.province_str,
        city_str: row.city_str,
        id: row.id
      };
      this.form = form;
      this.getProvince();
    },
    async handleDelete(row) {
      try {
        await delFreight({ id: row.id });
        this.$message({
          message: "删除成功",
          type: "success"
        });
        this.getList();
      } catch (error) {
        this.$message.error("删除失败");
        console.log(error);
      }
    },
    //抽屉
    handleClose(done) {
      this.resetForm("form");
      const form = {
        address: "",
        num: "",
        money: "",
        type: "",
        province_str: [],
        city_str: [],
        data: "",
        id: ""
      };
      this.form = form;
      this.drawer = false;
      done();
    },
    subCancel() {
      this.resetForm("form");
      const form = {
        address: "",
        num: "",
        money: "",
        type: "",
        province_str: [],
        city_str: [],
        data: "",
        id: ""
      };
      this.form = form;
      this.drawer = false;
    },
    onSubmit() {
      console.log(this.form);
      if (this.form.type == 1) {
        this.form.num = 0;
      }
      this.$refs["form"].validate(async valid => {
        if (valid) {
          if (this.title === "添加") {
            if (this.form.type == 1) {
              console.log(this.form.data);
              this.form.province_str = [];
              this.form.data.forEach(item => {
                console.log(item);
                this.form.province_str.push(item[0]);
              });
            } else if (this.form.type == 2) {
              this.form.data.forEach(item => {
                this.form.city_str.push(item[item.length - 1]);
              });
            }
            this.form.data = JSON.stringify(this.form.data);

            const res = await addFreight({ ...this.form });
            console.log(res);
            if (res.st === 1) {
              this.resetForm("form");
              const form = {
                address: "",
                num: "",
                money: "",
                type: "",
                province_str: [],
                city_str: [],
                data: "",
                id: ""
              };
              this.form = form;
              this.getList();
              this.$message({
                message: "添加成功",
                type: "success"
              });
              this.drawer = false;
            } else {
              console.log(res);
              this.$message.error("添加失败");
            }
          } else if (this.title === "编辑") {
            if (this.form.type == 1) {
              this.form.province_str = [];
              this.form.data.forEach(item => {
                console.log(item);
                this.form.province_str.push(item[0]);
              });
            } else if (this.form.type == 2) {
              this.form.data.forEach(item => {
                this.form.city_str.push(item[item.length - 1]);
              });
              this.form.city_str = Array.from(new Set(this.form.city_str));
            }
            this.form.data = JSON.stringify(this.form.data);
            const res = await editFreight({ ...this.form });
            console.log(res);
            if (res.st === 1) {
              this.resetForm("form");
              const form = {
                address: "",
                num: "",
                money: "",
                type: "",
                province_str: [],
                city_str: [],
                id: "",
                data: ""
              };
              this.form = form;
              this.getList();
              this.$message({
                message: "编辑成功",
                type: "success"
              });
              this.drawer = false;
            } else {
              console.log(res);
              this.$message.error("编辑失败");
            }
          }
        }
      });
    },
    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  }
};
</script>

<style lang="scss" scoped>
.query-card {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  ::v-deep .el-form {
    display: flex;
  }
}
.box-card {
  margin-bottom: 20px;
}
.search {
  display: flex;
  align-items: center;
}
::v-deep .el-input--medium .el-input__inner {
  width: 360px;
}
::v-deep .el-textarea__inner {
  width: 360px;
}
::v-deep .el-drawer.rtl {
  width: 650px !important;
  overflow: auto;
}
</style>
<style>
.el-tooltip__popper.is-dark {
  width: 500px !important;
}
</style>